package com.knife.excel;

import com.knife.entity.WorkOrderBean;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * create by yongli on 2021-11-11 15:52
 * 文件写模板
 */

public class ExcelWrite {


    static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");


    public static void main(String[] args) {
        ExcelWrite excelWrite = new ExcelWrite();
        excelWrite.test();
    }

    public void test() {

        // 将改写的excel文件写入新的
        String path = "/Users/yongli/Desktop/blade11.xlsx";
        String path2 = "/Users/yongli/Desktop/blade11.xlsx";
        int k = 0;

        try {
            File file = new File(path);
            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0);
            int col = sheet.getRow(0).getPhysicalNumberOfCells();
            int num = sheet.getLastRowNum();

            List<WorkOrderBean> beanList = new ArrayList<>();
            // 从第2行开始读取
            for (int i = 1; i < num + 1; i++) {
                Thread.sleep(2);
                // 毫秒发射器
                String code = "GZ88" + sdf2.format(new Date());
                Row row = sheet.getRow(i);
                Cell cell = row.getCell(0);
                cell.setCellValue(code);
            }

            // work不能关闭
//            workbook.close();

//            在引用流中，就是不能用原来的空间了，也就是原来的名字
//            FileOutputStream out = new FileOutputStream(path);
//            workbook.write(out);
//            out.flush();
//            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void test3() {

        // 将改写的excel文件写入新的
        String path = "/Users/yongli/Desktop/ge11.xlsx";
        String path2 = "/Users/yongli/Desktop/ge112.xlsx";
        int k = 0;

        try {
            File file = new File(path);
            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0);
            int col = sheet.getRow(0).getPhysicalNumberOfCells();
            int num = sheet.getLastRowNum();

            List<WorkOrderBean> beanList = new ArrayList<>();
            // 从第2行开始读取
            for (int i = 1; i < num + 1; i++) {
                Thread.sleep(2);
                // 毫秒发射器
                String code = "GZ88" + sdf2.format(new Date());
                Row row = sheet.getRow(i);
                Cell cell = row.getCell(0);
                cell.setCellValue(code);
            }

            // File不可以关闭，但是Stream可以关闭
            FileOutputStream out = new FileOutputStream(path2);
            // workBook可以整个的写入
            workbook.write(out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
